<template>
  <div class="growth-container">
    <!-- 儿童选择器 -->
    <div class="selector-card">
      <el-card class="children-selector">
        <div class="selector-header">
          <el-select
            v-model="currentChildId"
            placeholder="请选择儿童"
            @change="handleChildChange"
          >
            <el-option
              v-for="child in children"
              :key="child.id"
              :label="child.name"
              :value="child.id"
            >
              <div class="child-option">
                <el-avatar :src="child.avatar" :size="32" />
                <span class="child-name">{{ child.name }}</span>
              </div>
            </el-option>
          </el-select>
          <el-button type="primary" :icon="Plus" @click="handleAddRecord">
            添加记录
          </el-button>
        </div>
      </el-card>
    </div>

    <template v-if="currentChildId">
      <!-- 成长数据卡片 -->
      <div class="data-cards">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card class="metric-card">
              <template #header>
                <div class="card-header">
                  <span>身高</span>
                  <el-tag type="success" size="small">标准</el-tag>
                </div>
              </template>
              <div class="metric-value">
                <span class="number">{{ currentGrowth.height }}</span>
                <span class="unit">cm</span>
              </div>
              <div class="metric-change">
                <span class="label">较上次</span>
                <span :class="['value', changes.height >= 0 ? 'positive' : 'negative']">
                  {{ changes.height >= 0 ? '+' : '' }}{{ changes.height }}cm
                </span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="metric-card">
              <template #header>
                <div class="card-header">
                  <span>体重</span>
                  <el-tag type="success" size="small">标准</el-tag>
                </div>
              </template>
              <div class="metric-value">
                <span class="number">{{ currentGrowth.weight }}</span>
                <span class="unit">kg</span>
              </div>
              <div class="metric-change">
                <span class="label">较上次</span>
                <span :class="['value', changes.weight >= 0 ? 'positive' : 'negative']">
                  {{ changes.weight >= 0 ? '+' : '' }}{{ changes.weight }}kg
                </span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="metric-card">
              <template #header>
                <div class="card-header">
                  <span>BMI</span>
                  <el-tag type="warning" size="small">偏低</el-tag>
                </div>
              </template>
              <div class="metric-value">
                <span class="number">{{ currentGrowth.bmi }}</span>
              </div>
              <div class="metric-change">
                <span class="label">较上次</span>
                <span :class="['value', changes.bmi >= 0 ? 'positive' : 'negative']">
                  {{ changes.bmi >= 0 ? '+' : '' }}{{ changes.bmi }}
                </span>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 成长曲线 -->
      <el-card class="growth-chart">
        <template #header>
          <div class="card-header">
            <span>成长曲线</span>
            <el-radio-group v-model="chartType" size="small">
              <el-radio-button label="height">身高曲线</el-radio-button>
              <el-radio-button label="weight">体重曲线</el-radio-button>
              <el-radio-button label="bmi">BMI曲线</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div class="chart-container">
          <div id="growthChart" style="width: 100%; height: 100%;"></div>
        </div>
      </el-card>

      <!-- 历史记录 -->
      <el-card class="history-records">
        <template #header>
          <div class="card-header">
            <span>历史记录</span>
          </div>
        </template>
        <el-table :data="growthRecords" stripe style="width: 100%">
          <el-table-column prop="date" label="记录日期" width="120" />
          <el-table-column prop="height" label="身高(cm)" width="100" />
          <el-table-column prop="weight" label="体重(kg)" width="100" />
          <el-table-column prop="bmi" label="BMI" width="80" />
          <el-table-column prop="evaluation" label="评估" />
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button-group>
                <el-button 
                  type="primary" 
                  text 
                  @click="handleEdit(scope.row)"
                >
                  编辑
                </el-button>
                <el-button 
                  type="danger" 
                  text 
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </template>

    <!-- 未选择儿童时的提示 -->
    <el-empty v-else description="请先选择儿童" />

    <!-- 添加记录对话框 -->
    <el-dialog
      v-model="addRecordDialogVisible"
      title="添加成长记录"
      width="400px"
      class="neumorphic-dialog"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form :model="recordForm" label-width="80px" class="neumorphic-form">
        <el-form-item label="日期">
          <el-date-picker
            v-model="recordForm.date"
            type="date"
            placeholder="选择日期"
            class="neumorphic-input w-full"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="身高">
          <el-input
            v-model="recordForm.height"
            class="neumorphic-input w-full"
            placeholder="请输入身高(cm)"
            type="number"
            step="0.1"
          >
            <template #append>cm</template>
          </el-input>
        </el-form-item>
        <el-form-item label="体重">
          <el-input
            v-model="recordForm.weight"
            class="neumorphic-input w-full"
            placeholder="请输入体重(kg)"
            type="number"
            step="0.1"
          >
            <template #append>kg</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            @click="addRecordDialogVisible = false"
            class="neumorphic-button cancel-button"
          >
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleSaveRecord"
            class="confirm-button"
          >
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, onUnmounted, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { getChildList } from '@/api/child'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken, isLoggedIn } from '@/utils/auth'
import { get, post } from '@/utils/request'
import * as echarts from 'echarts'

// 儿童列表
const children = ref([])
const currentChildId = ref(null)
const loading = ref(false)

// 获取儿童列表
const fetchChildren = async () => {
  try {
    // 检查登录状态
    if (!isLoggedIn()) {
      ElMessage.warning('用户未登录或登录已过期，请重新登录')
      return
    }

    loading.value = true
    console.log('开始获取儿童列表，Token:', getToken())
    
    const res = await getChildList()
    console.log('获取儿童列表响应:', res)
    
    children.value = res.map(child => ({
      id: child.id,
      name: child.name,
      avatar: child.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    }))
    
    // 如果有儿童，默认选中第一个并获取其生长记录
    if (children.value.length > 0 && !currentChildId.value) {
      currentChildId.value = children.value[0].id
      await getGrowthRecords(children.value[0].id)
    }
  } catch (error) {
    console.error('获取儿童列表失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status
    })
    
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
    } else if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('获取儿童列表失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 图表类型
const chartType = ref('height')

// 当前成长数据
const currentGrowth = reactive({
  height: 0,
  weight: 0,
  bmi: 0
})

// 成长记录列表
const growthRecords = ref([])

// 添加记录对话框
const addRecordDialogVisible = ref(false)
const recordForm = reactive({
  date: new Date(),
  height: '',
  weight: ''
})

// 在 script setup 顶部添加响应式变量
const currentEditId = ref(null)
const isEditing = ref(false)

// 获取生长记录
const getGrowthRecords = async (childId) => {
  try {
    console.log('开始获取生长记录，childId:', childId)
    const res = await get(`/user/growthRecord/childinfo?childId=${childId}`)
    console.log('后端返回的原始数据:', res)
    
    // 直接使用后端返回的已排序数据
    growthRecords.value = res
    console.log('设置到 growthRecords 的数据:', growthRecords.value)
    
    // 更新当前生长数据（取第一条记录，即最新记录）
    if (growthRecords.value.length > 0) {
      const latest = growthRecords.value[0]
      console.log('取出的最新记录 (index 0):', latest)
      currentGrowth.height = latest.height
      currentGrowth.weight = latest.weight
      currentGrowth.bmi = latest.bmi
      console.log('更新后的当前生长数据:', { ...currentGrowth })
    }
  } catch (error) {
    console.error('获取生长记录失败:', error)
    ElMessage.error('获取生长记录失败')
  }
}

// 处理儿童切换
const handleChildChange = async (childId) => {
  currentChildId.value = childId
  if (childId) {
    await getGrowthRecords(childId)
  }
}

// 处理添加记录
const handleAddRecord = () => {
  if (!currentChildId.value) {
    ElMessage.warning('请先选择儿童')
    return
  }
  // 重置表单
  recordForm.date = new Date()
  recordForm.height = ''
  recordForm.weight = ''
  // 重置编辑状态
  isEditing.value = false
  currentEditId.value = null
  // 打开对话框
  addRecordDialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  // 设置表单数据
  recordForm.date = row.date
  recordForm.height = row.height
  recordForm.weight = row.weight
  currentEditId.value = row.id
  // 打开对话框
  addRecordDialogVisible.value = true
  isEditing.value = true
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 修改删除接口的调用
    await post(`/user/growthRecord/del/${row.id}`)
    ElMessage.success('删除成功')
    // 刷新记录列表
    await getGrowthRecords(currentChildId.value)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 修改保存记录方法
const handleSaveRecord = async () => {
  try {
    // 表单验证
    if (!recordForm.date || !recordForm.height || !recordForm.weight) {
      ElMessage.warning('请填写完整的记录信息')
      return
    }

    // 构造请求数据
    const data = {
      childId: currentChildId.value,
      height: recordForm.height,
      weight: recordForm.weight,
      recordTime: recordForm.date
    }

    if (isEditing.value) {
      // 编辑模式，添加id字段
      data.id = currentEditId.value
      await post('/user/growthRecord/update', data)
      ElMessage.success('更新记录成功')
    } else {
      // 添加模式
      await post('/user/growthRecord/add', data)
      ElMessage.success('添加记录成功')
    }
    
    // 关闭对话框
    addRecordDialogVisible.value = false
    // 重置编辑状态
    isEditing.value = false
    currentEditId.value = null
    // 刷新记录列表
    await getGrowthRecords(currentChildId.value)
  } catch (error) {
    console.error(isEditing.value ? '更新记录失败:' : '添加记录失败:', error)
    ElMessage.error(isEditing.value ? '更新记录失败，请稍后重试' : '添加记录失败，请稍后重试')
  }
}

// 计算变化值
const changes = computed(() => {
  if (growthRecords.value.length < 2) {
    return {
      height: 0,
      weight: 0,
      bmi: 0
    }
  }
  
  // 直接使用前两条记录计算变化值
  const latest = growthRecords.value[0]
  const previous = growthRecords.value[1]
  
  return {
    height: +(latest.height - previous.height).toFixed(1),
    weight: +(latest.weight - previous.weight).toFixed(1),
    bmi: +(latest.bmi - previous.bmi).toFixed(1)
  }
})

// 图表实例
let chartInstance = null

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || growthRecords.value.length === 0) {
    return
  }
    // 对记录按日期进行排序
  const sortedRecords = [...growthRecords.value].sort((a, b) => {
    const dateA = new Date(a.date)
    const dateB = new Date(b.date)
    return dateA - dateB
  })
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const data = params[0]
        const record = sortedRecords[data.dataIndex]
        const date = new Date(record.date)
        return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日<br/>${data.seriesName}: ${data.value}${
          chartType.value === 'height' ? 'cm' : 
          chartType.value === 'weight' ? 'kg' : ''
        }`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: sortedRecords.map(record => {
        const date = new Date(record.date)
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
      }),
      boundaryGap: false,
      axisLabel: {
        show: true,
        formatter: function(value) {
          const date = new Date(value)
          // 只显示月/日，年份在tooltip中显示
          return `${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`
        },
        interval: 'auto',  // 自动计算间隔
        rotate: 0,         // 不旋转
        align: 'center',
        margin: 8,
        fontSize: 12
      },
      axisTick: {
        show: true,
        alignWithLabel: true
      },
      axisLine: {
        show: true
      }
    },
    yAxis: {
      type: 'value',
      name: chartType.value === 'height' ? '身高(cm)' : 
            chartType.value === 'weight' ? '体重(kg)' : 'BMI',
      nameTextStyle: {
        padding: [0, 0, 0, 40]
      },
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: chartType.value === 'height' ? '身高' : 
              chartType.value === 'weight' ? '体重' : 'BMI',
        type: 'line',
        data: sortedRecords.map(record => {
          switch (chartType.value) {
            case 'height':
              return record.height
            case 'weight':
              return record.weight
            case 'bmi':
              return record.bmi
          }
        }),
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(64, 158, 255, 0.3)'
            },
            {
              offset: 1,
              color: 'rgba(64, 158, 255, 0.1)'
            }
          ])
        }
      }
    ]
  }
  
  chartInstance.setOption(option, true)
}

// 初始化图表
const initChart = () => {
  console.log('开始初始化图表')
  const chartDom = document.getElementById('growthChart')
  if (!chartDom) {
    console.log('未找到图表DOM元素')
    return
  }
  
  // 销毁已存在的实例
  if (chartInstance) {
    console.log('销毁已存在的图表实例')
    chartInstance.dispose()
  }
  
  console.log('创建新的图表实例')
  chartInstance = echarts.init(chartDom)
  chartInstance.showLoading()
  
  if (growthRecords.value.length > 0) {
    console.log('有生长记录，更新图表')
    updateChart()
    chartInstance.hideLoading()
  } else {
    console.log('没有生长记录，保持加载状态')
  }
}

// 监听数据变化
watch([growthRecords, chartType], () => {
  console.log('数据或图表类型发生变化，准备更新图表')
  if (chartInstance) {
    if (growthRecords.value.length > 0) {
      updateChart()
      chartInstance.hideLoading()
    } else {
      chartInstance.showLoading()
    }
  } else {
    // 如果图表实例不存在但有数据，则初始化图表
    if (growthRecords.value.length > 0) {
      console.log('检测到数据但图表未初始化，开始初始化')
      nextTick(() => {
        initChart()
      })
    }
  }
}, { deep: true })

// 监听窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    console.log('窗口大小变化，重置图表大小')
    chartInstance.resize()
  }
}

onMounted(() => {
  fetchChildren()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.growth-container {
  padding: 24px;
}

.selector-card {
  margin-bottom: 24px;
}

.children-selector {
  background: linear-gradient(135deg, #4b6cb7 0%, #182848 100%);
  border: none;
  color: white;
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selector-header .el-select {
  width: 200px;
}

.child-option {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
}

.child-name {
  font-weight: 600;
  font-size: 16px;
}

.child-age {
  color: #909399;
  font-size: 14px;
}

.data-cards {
  margin-bottom: 24px;
}

.metric-card {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.metric-value {
  text-align: center;
  padding: 20px 0;
}

.metric-value .number {
  font-size: 36px;
  font-weight: 600;
  color: #333;
}

.metric-value .unit {
  font-size: 16px;
  color: #999;
  margin-left: 4px;
}

.metric-change {
  text-align: center;
  padding: 12px 0;
  background: #f8f9fa;
  border-top: 1px solid #f0f0f0;
}

.metric-change .label {
  color: #999;
  margin-right: 8px;
}

.metric-change .value {
  font-weight: 600;
}

.metric-change .positive {
  color: #67c23a;
}

.metric-change .negative {
  color: #f56c6c;
}

.growth-chart {
  margin-bottom: 24px;
}

.chart-container {
  height: 400px;
  padding: 20px;
  background: #fff;
}

.history-records {
  margin-bottom: 24px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background: #f8f9fa;
}

:deep(.el-button) {
  border-radius: 20px;
}

:deep(.el-dialog) {
  border-radius: 16px;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

/* 新拟态对话框样式 - 暗色风格 */
:deep(.neumorphic-dialog) {
  background: #1a1a1a;
  border-radius: 12px;
  box-shadow: 
    5px 5px 10px #0d0d0d,
    -5px -5px 10px #272727;
  border: none;
}

:deep(.neumorphic-dialog .el-dialog__header) {
  padding: 16px 20px;
  margin: 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
  background: #1a1a1a;
  border-radius: 12px 12px 0 0;
}

:deep(.neumorphic-dialog .el-dialog__title) {
  font-size: 16px;
  font-weight: 500;
  color: #e5e7eb;
}

:deep(.neumorphic-dialog .el-dialog__body) {
  padding: 20px;
  background: #1a1a1a;
}

:deep(.neumorphic-dialog .el-dialog__footer) {
  padding: 16px 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.05);
  background: #1a1a1a;
  border-radius: 0 0 12px 12px;
}

/* 新拟态表单控件样式 - 暗色风格 */
:deep(.neumorphic-input) {
  background: #1a1a1a !important;
  border: none !important;
  border-radius: 8px !important;
  box-shadow: 
    inset 3px 3px 6px #0d0d0d,
    inset -3px -3px 6px #272727 !important;
  color: #e5e7eb !important;
}

:deep(.neumorphic-input:focus),
:deep(.neumorphic-input:hover) {
  box-shadow: 
    inset 4px 4px 8px #0d0d0d,
    inset -4px -4px 8px #272727 !important;
}

:deep(.neumorphic-input .el-input__wrapper) {
  background: transparent !important;
  box-shadow: none !important;
}

:deep(.neumorphic-input .el-input__inner) {
  color: #e5e7eb !important;
}

:deep(.neumorphic-input .el-input-number__decrease),
:deep(.neumorphic-input .el-input-number__increase) {
  background: #262626 !important;
  border: none !important;
  color: #e5e7eb !important;
}

:deep(.neumorphic-input .el-input-number__decrease:hover),
:deep(.neumorphic-input .el-input-number__increase:hover) {
  background: #333333 !important;
}

:deep(.neumorphic-button) {
  background: #1a1a1a !important;
  border: none !important;
  border-radius: 8px !important;
  padding: 8px 16px !important;
  font-weight: 500 !important;
  transition: all 0.2s ease !important;
  box-shadow: 
    3px 3px 6px #0d0d0d,
    -3px -3px 6px #272727 !important;
  color: #e5e7eb !important;
}

:deep(.neumorphic-button:hover) {
  box-shadow: 
    4px 4px 8px #0d0d0d,
    -4px -4px 8px #272727 !important;
  transform: translateY(-1px);
}

:deep(.neumorphic-button:active) {
  box-shadow: 
    inset 3px 3px 6px #0d0d0d,
    inset -3px -3px 6px #272727 !important;
  transform: translateY(1px);
}

:deep(.confirm-button) {
  background: #3b82f6 !important;
  color: white !important;
  box-shadow: 
    3px 3px 6px rgba(0, 0, 0, 0.3),
    -3px -3px 6px rgba(255, 255, 255, 0.1) !important;
}

:deep(.confirm-button:hover) {
  box-shadow: 
    4px 4px 8px rgba(0, 0, 0, 0.3),
    -4px -4px 8px rgba(255, 255, 255, 0.1) !important;
}

:deep(.confirm-button:active) {
  box-shadow: 
    inset 3px 3px 6px rgba(0, 0, 0, 0.3),
    inset -3px -3px 6px rgba(255, 255, 255, 0.1) !important;
}

/* 表单项样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #e5e7eb !important;
}

/* 日期选择器暗色样式 */
:deep(.el-date-editor .el-input__wrapper) {
  background: transparent !important;
  box-shadow: none !important;
}

:deep(.el-date-editor .el-input__inner) {
  color: #e5e7eb !important;
}

:deep(.el-date-editor .el-input__prefix-inner i) {
  color: #e5e7eb !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 工具类 */
.w-full {
  width: 100%;
}
</style> 